package com.jjkj.controller;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jjkj.base.common.R;
import com.jjkj.base.exception.BusinessException;
import com.jjkj.base.interceptor.JwtInterceptor;
import com.jjkj.domain.dto.LoginUserDto;
import com.jjkj.model.User;
import com.jjkj.service.UserService;
import com.jjkj.validator.LoginValidator;
import io.jboot.db.model.Columns;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.List;

@RequestMapping("/")
@Api()
public class IndexController extends JbootController {

    @Inject
    private UserService userService;

    public void index() {
        renderJson(new Object());
    }

    /**
     * 登录 基于 jwt
     */
    @ApiOperation(value = "登录", httpMethod = "POST")
    @Before({ POST.class, LoginValidator.class })
    @Clear(JwtInterceptor.class)
    public void login() {
        LoginUserDto loginUserDto = getRawObject(LoginUserDto.class);

        User user = userService.findFirstByColumns(
                Columns.create().add("username", loginUserDto.getUsername())
                    .add("password", HashKit.md5(loginUserDto.getPassword()))
        );

        if(user == null) {
            throw new BusinessException("用户名或者密码错误");
        }

        setJwtAttr("userId", user.getId() + "");

        renderJson(R.success(Ret.create("token", createJwtToken())));
    }

    @Clear()
    public void test(){
        List<Record> users = Db.use("oa").find("select * from user limit 20");
        renderJson(R.success(users));
    }


    @Clear()
    public void test2(String username){
        int update = Db.use("oa").update("update user set user_name = ? where uid = 1", username);
        renderJson(R.success(update));
    }
}